<?php


namespace app\api\controller;

use app\api\model\MeetModel;
use app\api\model\MeetSignModel;
use app\api\model\MeetUserModel;
use app\api\model\room\RoomModel;
use app\common\controller\Api;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\Response;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;


class MeetSign extends Api
{
// 无需登录的接口,*表示全部
    protected $noNeedLogin = ['info','success'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 列表
    public function lists()
    {
        $limit = input('limit') ? input('limit') : '15';
        $meet_id = input('meet_id') ? input('meet_id') : '0';
        $meet = MeetModel::get($meet_id);
        if (!$meet) {
            $this->error('会议不存在');
        }
       $attend_meet_ids =  $meet['attend_meet_ids'];
        //0=全部,1=签到 ,2=请假，3=缺勤
        if ( input('status') == 1) {
            $user_ids = MeetSignModel::where('status in(1)')
                ->where(['meet_id'=> $meet_id])
                ->column('user_id');
            $list = MeetUserModel::where( 'id','in',$user_ids)
                ->field("id,nickname,username,avatar")
                ->order("id desc")
                ->paginate($limit)->each(function ($item, $key) use (&$meet) {
                    $item['meet_id'] = $meet['id'];
                    $sign = MeetSignModel::where( "meet_id", "in",$meet['id']  )
                        ->where(['user_id'=>$item['id']])
                        ->field("id,title,createtime,status")
                        ->find();
                    $start = strtotime($meet['start_time']);
                    $is_late = 0;
                    if($sign){
                        if($sign['createtime'] > $start){
                            $is_late = 1;
                        }
                    }
                    $item['is_late'] = $is_late; //1=迟到 0=正常
                    $title = $is_late==1?'迟到签到':'签到成功';
                    $item['sign_id'] = $sign['id'];
                    $item['title'] = $title;
                    $item['createtime'] = date("Y-m-d H:i",  $sign['createtime']);
                    return $item;
                })
                ->toArray();
          }else if ( input('status') == 2) {
            $user_ids = MeetSignModel::where('status in(4)')
                ->where(['meet_id'=> $meet_id])
                ->column('user_id');
               $list = MeetUserModel::where('id','in',$user_ids)
                   ->field("id,nickname,username,avatar")
                   ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$meet) {
                       $item['meet_id'] = $meet['id'];
                       $sign = MeetSignModel::where("meet_id", "in", $meet['id'])->where(['user_id' => $item['id']])->field("title,createtime,status")->find();
                       $item['is_late'] = 1; //1=迟到 0=正常
                       $item['sign_id'] = '';
                       $item['title'] = '个人原因，有事不能参加会议';
                       $item['createtime'] = '';

                       return $item;
                   })
                   ->toArray();
        }else if ( input('status') ==3) {
            $user_ids = MeetSignModel::where('status in(3)')
                ->where(['meet_id'=> $meet_id])
                ->column('user_id');
            //$attend_meet_arr = explode(",",$attend_meet_ids);
            //$diff = array_diff($attend_meet_arr,$user_ids  );
           // print_r($diff);
            $list = MeetUserModel::where( 'id','in',$user_ids)
                ->field("id,nickname,username,avatar")
                ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$meet) {
                    $item['meet_id'] = $meet['id'];
                    $sign = MeetSignModel::where( "meet_id", "in",$meet['id']  )->where(['user_id'=>$item['id']])->field("title,createtime,status")->find();
                    $item['is_late'] = 1; //1=迟到 0=正常
                    $item['sign_id'] = '';
                    $item['title'] = '个人原因，有事不能参加会议';
                    $item['createtime'] = '';
                    return $item;
                })
                ->toArray();
        }else{
            $user_ids = MeetSignModel::where('status in(1,2,3,4)')
                ->where(['meet_id'=> $meet_id])
                ->column('user_id');
            $list = MeetUserModel::where('id','in',$user_ids)
                ->field("id,nickname,username,avatar")
                ->order("id desc")
            ->paginate($limit)->each(function ($item, $key) use (&$meet) {
                    $item['meet_id'] = $meet['id'];
                    $sign = MeetSignModel::where( "meet_id", "in",$meet['id']  )
                        ->where(['user_id'=>$item['id']])
                        ->field("title,createtime,status")
                        ->find();
                    $item['is_late'] = 1; //1=迟到 0=正常
                    $item['sign_id'] = '';
                    $item['title'] = '';
                    $item['createtime'] = '';
                    return $item;
                })
                ->toArray();
        }

        $this->success('成功', $list);
    }


    // 数据导出
    public function excel()
    {
        $limit = input('limit') ? input('limit') : '15';
        $map = [];
        if (!empty(input('status'))) {
            $map = [
                'status' => input('status'),
            ];
        }
        if (!empty(input('user_id'))) {
            $map['user_id'] = input('user_id');
        }
        $List = MeetSignModel::where($map)->whereNull('deletetime')->select();
        $newExcel = new Spreadsheet();  //创建一个新的excel文档
        $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
        //设置宽度为true,不然太窄了
        $newExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $newExcel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
        $newExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $newExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
        $newExcel->getActiveSheet()->getColumnDimension('E')->setWidth(40);
        $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
        //获取数据库的数据。//使用模型
        $objSheet->setTitle('班级表');  //设置当前sheet的标题
        //设置第一栏的标题
        $objSheet->setCellValue('A1', '用户')
            ->setCellValue('B1', '会议')
            ->setCellValue('C1', '状态')
            ->setCellValue('D1', '会议时间')
            ->setCellValue('E1', '签到时间');
        foreach ($List as $k => $val) {
            $k = $k + 2;
            $user = (new MeetUserModel())->where(['id' => $val['user_id']])->find();
            $meet = (new MeetModel())->where(['id' => $val['meet_id']])->find();
            $statusName = $val['status'] == 1 ? "正常" : ($val['status'] == 2 ? "迟到" : "缺席");
            $objSheet->setCellValue('A' . $k, $user['username'])
                ->setCellValue('B' . $k, $meet['title'])
                ->setCellValue('C' . $k, $statusName)
                ->setCellValue('D' . $k, $meet['start_time'])
                ->setCellValue('E' . $k, date("Y-m-d H:i:s", $val['createtime']));
        }
        $this->downloadExcel($newExcel, '表1', 'Xls');
    }


//公共文件，用来传入xls并下载
    public function downloadExcel($newExcel, $filename, $format)
    {
        ob_end_clean();
        // $format只能为 Xlsx 或 Xls
        if ($format == 'Xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        } elseif ($format == 'Xls') {
            header('Content-Type: application/vnd.ms-excel');
        }

        header("Content-Disposition: attachment;filename="
            . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($newExcel, $format);

        $objWriter->save('php://output');

        //通过php保存在本地的时候需要用到
        //$objWriter->save($dir.'/demo.xlsx');

        //以下为需要用到IE时候设置
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
//         If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        exit;
    }

    // 二维码信息
    public function qr_info()
    {
        $id = input('meet_id');
        $info = MeetModel::get($id);
        if (!$info) {
            $this->error('会议不存在');
        }
        $time = $this->getTime();
        $url = $this->serverUrl() . '/api/meet_sign/add?sign_way=' . $info['sign_way'] . '&time=' . $time . '&meet_id=' . $id;
        //生成二维码 传生成二维码的文本内容
        $qrCode = $this->build($url);
        $qrCodeUrl = $this->serverUrl() . '/uploads/qrcode/' . $qrCode;
        $this->success('返回成功', ["title" => $info['title'],"start_time" => $info['start_time']  ,"time" => $time, "hi" => date("h:i"), "url" => $url, 'qrCodeUrl' => $qrCodeUrl]);
    }


    // 签到成功
    public function ok()
    {
        $user = $this->auth->getUserinfo();
        // print_r($user);
  /*      print <<<EOT

     <div class="slidecont">hi，{$user['username']}</div>
     <div class="newcontainter">
       <H3> 签到 操作成功！</H3>
     </div>
      <a href="" title=" " target="_blank">返回</a>
 EOT;*/
    }

    // 签到详情
    public function info()
    {
        $input = input();
        $input['user_id'] = $this->auth->id;
        $info = MeetSignModel::add($input);
        if ($info['status'] == 1) {
            header("Location: https://huiyi.bigchun.com/api/meet_sign/ok");
        } else {
            $this->error(  $info['msg']);
        }
    }

    // 详情
    public function detail()
    {
        $id = input('id');
        $info = MeetSignModel::detail($id);
        $this->success('成功', $info);
    }

    public function add()
    {
        $input = input();
        $input['user_id'] = $this->auth->id;
        $res = MeetSignModel::where(['meet_id' => $input['meet_id'], 'user_id' => $input['user_id']])->find();
        if($res){
            $this->error('您已签到');
        }
        $info = MeetSignModel::add($input);
        if ($info['status'] == 1) {
            $this->success(  $info['msg'],$info);
        } else {
            $this->error(  $info['msg'],$info);
        }
    }


    public function ask_leave()
    {
        $input = input();
        $meet_id = input('meet_id');
        $model = MeetModel::get($meet_id);
        if (!$model) {
            $this->error('会议不存在');
        }

        $checkRole = MeetModel::checkActionRole($model,$this->auth->id,'attend_meet');
        if($checkRole['status'] == 0 ){
            $this->error($checkRole['msg']);
        }

        $input['status'] = 4;
        $input['user_id'] = $this->auth->id;
        $model = new MeetSignModel($input);
        $res = $model->where(['meet_id' => $input['meet_id'], 'user_id' => $this->auth->id])->find();
        if (!$res) {
            $row = $model->allowField(true)->save();
            $this->success('请假成功');
        } else {
            $this->error('已经请假');
        }
    }

    public function edit()
    {
        $user = $this->auth->getUser();
        $input = input();
        $model = new MeetSignModel();
        if (!empty(input('createtime'))) {
            $input['createtime'] = strtotime($input['createtime']);
        }
        $row = $model->allowField(true)->save($input, ['id' => $input['id'], 'user_id' => $this->auth->id]);
        $this->success('修改成功', $row);
    }

    public function delete()
    {
        $input = input();
        $model = new MeetSignModel();
        $row = $model->where(['id' => $input['id'], 'user_id' => $this->auth->id])->delete();
        if ($row) {
            $this->success('删除成功', $row);
        } else {
            $this->error('删除失败');
        }
    }

    public function getTime()
    {

        $time = floor(date("i") / 15) . "-" . date("H");
        return $time;
    }

    public function serverUrl()
    {
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        return $http_type . $_SERVER['HTTP_HOST'];
    }

    // 生成二维码
    public function build($text)
    {
        $config = get_addon_config('qrcode');
        $params = $this->request->get();
        $params = array_intersect_key($params, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));

        $params['text'] = $text;
        $params['label'] = '';
        $qrCode = \addons\qrcode\library\Service::qrcode($params);

        $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

        $response = Response::create()->header("Content-Type", $mimetype);

        // 直接显示二维码
        // header('Content-Type: ' . $qrCode->getContentType());
        // $response->content($qrCode->writeString());

        $code_name = "";
        // 写入到文件
        // if ($config['writefile']) {
        $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
        if (!is_dir($qrcodePath)) {
            @mkdir($qrcodePath);
        }
        if (is_really_writable($qrcodePath)) {
            $filePath = $qrcodePath . md5(implode('', $params)) . '.' . $config['format'];
            $qrCode->writeFile($filePath);
            $code_name = md5(implode('', $params)) . '.' . $config['format'];
        }
        //  }

        return $code_name;
    }

}
